<template>
    <div class="app-container">
      <el-form :model="queryParamsInit" ref="queryFormInit" size="small" :inline="true" v-show="showSearch"
               label-width="90px">
        <el-form-item label="规则分类" prop="id">
          <treeselect style="width: 400px;" v-model="queryParamsInit.id"
                      :show-count="true" @select="getCheckObject"
                      :options="regulationRuleList" placeholder="请选择规则分类"/>
        </el-form-item>

        <el-form-item label="数据库类型" prop="dataBaseType">
          <el-select  @change="changeDataBaseType($event)" filterable clearable v-model="queryParamsInit.dataBaseType" placeholder="请选择数据库类型">
            <el-option
              v-for="dict in dict.type.report_database_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          <span slot="label">
            <el-tooltip content="用于导出的时候选择对应数据库类型的数据" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            数据库类型
        </span>
        </el-form-item>
        <el-form-item label="版本号" prop="hisVersion">
          <el-select @change="changeHisVersion($event)" clearable filterable v-model="queryParamsInit.hisVersion"
                     placeholder="请选择版本号">
            <el-option
              v-for="dict in hisVersions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
          <span slot="label">
            <el-tooltip content="用于导出的时候选择对应版本的数据，或者按照版本读取文件" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            版本号
        </span>
        </el-form-item>
      </el-form>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="导出方式" prop="exportType">
          <el-select filterable clearable v-model="queryParams.exportType"  placeholder="请选择规则导出方式">
            <el-option
              v-for="exportType in exportTypes"
              :key="exportType.value"
              :label="exportType.label"
              :value="parseInt(exportType.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属客户" prop="customerId">
          <treeselect style="width: 300px;" v-model="queryParams.customerId" :show-count="true"
                      :multiple="false"
                      :disable-branch-nodes="true"
                      @keyup.enter.native="handleQuery"
                      :options="customerTree"  placeholder="请输入所属客户" />
          <span slot="label">
            <el-tooltip content="用于导出的时候相同业务主键的数据，优选取对应客户的数据" placement="top">
            <i class="el-icon-question"></i>
            </el-tooltip>
            所属客户
        </span>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-download"
            size="mini"
            @click="downRuleExecl"
            v-hasPermi="['reportworld:rule:export']"
          >导出规则
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-upload"
            size="mini"
            @click="readExecl"
            v-hasPermi="['reportworld:rule:readExecl']"
          >读取规则文件</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border="border" max-height="550px" v-loading="loading" :data="objectList"
                @selection-change="handleSelectionChange" @row-click="rowClick"
                @sort-change="handleSortChange" :row-style="tableRowStyle" ref="para">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column  type="index" min-width="5%"  label="编号"> </el-table-column>
        <el-table-column label="校验对象" width="300"  align="center" prop="checkCode" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="引用表名" width="300" align="center" prop="sourceTableId" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="引用表中文名" width="300"  align="center" prop="sourceTableName" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="校验对象描述" width="300" align="center" prop="describes" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="检验对象类型" width="300" align="center" prop="subType" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="分类" width="300" align="center" prop="ruleTypeId" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
        <el-table-column label="类型" width="300" align="center" prop="types" :show-overflow-tooltip="true" sortable="custom" :sort-orders="['descending', 'ascending']"/>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <el-dialog v-if="upload.open" :title="upload.title" :close-on-click-modal ="false" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .XLSX"
          :headers="upload.headers"
          :action="upload.url + '?hisVersion=' + this.queryParamsInit.hisVersion"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport" /> 生成SQL(不直接到脚本提交页面)
            </div>
            <span>仅允许导入xlsx格式文件。</span>
            <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>-->
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </el-dialog>

      <el-dialog v-if="openScript"  :close-on-click-modal ="false"  :title="titleScript" @ :visible.sync="openScript" width="1300px" append-to-body>
        <scriptInfo :scriptSqlInfo="scriptSqlInfo" :hisVersion="hisVersion" ref="child"> </scriptInfo >
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileFormChild">确 定</el-button>
          <el-button @click="openScript = false">关 闭</el-button>
        </div>
      </el-dialog>
    </div>
</template>

<script>
    import { listCheckType,init } from "@/api/reportworld/rule";
    import { getTableRowStyle } from "@/utils/yss";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    import { getToken } from "@/utils/auth";
    import scriptInfo from "@/views/reportworld/script/info";

    export default {
      name: "rule",
      components: {
        Treeselect,
        scriptInfo
      },
      dicts: ['report_database_type','report_version'],
      data() {
        return {
          exportTypes: [
            {
              value: 1,
              label: "规则分类"
            },
            {
              value: 2,
              label: "校验对象"
            }
          ],
          // 遮罩层
          loading: true,
          // 选中数组
          ids: [],
          // 非单个禁用
          single: true,
          // 非多个禁用
          multiple: true,
          // 显示搜索条件
          showSearch: true,
          // 总条数
          total: 0,
          // 报表基本信息表表格数据
          objectList: [],
          // 弹出层标题
          title: "",
          // 是否显示弹出层
          open: false,
          // 弹出框
          titleScript: "",
          openScript:false,
          // 监管规则下拉框
          regulationRuleList: [],
          regulationName:'',
          hisVersions:[],
          nodeName:null,
          // 所属客户
          customerTree: [],
          // 查询参数
          queryParams: {
            pageNum: 1,
            pageSize: 50,
            exportType:1,
            id: null,
          },
          queryParamsInit:{
            id:null,
            dataBaseType:'ORACLE',
            hisVersion:null
          },
          // 导入参数
          upload: {
            // 是否显示弹出层
            open: false,
            // 弹出层标题
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/reportworld/rule/readExecl"
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {
            id: [
              {required: true, message: "不能为空", trigger: "blur"}
            ],
          }
        };
      },
        created() {
            this.init();
        },
        methods: {
          /** 查询报表基本信息表列表 */
          init() {
            this.loading = true;
            init().then(response => {
            this.regulationRuleList = response.regulationRuleList;
            this.hisVersions =  response.hisVersions;
            this.customerTree=response.customerTree;
            this.loading = false;
          });
          },
          changeHisVersion(value){
            this.queryParamsInit.hisVersion=value;
            this.getList();
          },
          changeDataBaseType(value){
            this.queryParamsInit.dataBaseType=value;
            this.getList();
          },
          getCheckObject(value){
            this.queryParamsInit.ruleTypeId=value.id;
            this.nodeName= value.label;
            this.getList();
          },
            /** 查询报表基本信息表列表 */
            getList() {
                this.objectList = [];
                this.loading = true;
                this.queryParams.ruleTypeId=this.queryParamsInit.ruleTypeId;
                this.queryParams.dataBaseType=this.queryParamsInit.dataBaseType;
                this.queryParams.hisVersion=this.queryParamsInit.hisVersion;
              listCheckType(this.queryParams).then(response => {
                this.objectList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
            },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length!==1
            this.multiple = !selection.length
        },
        /** 排序触发事件 */
        handleSortChange(column, prop, order) {
            this.queryParams.orderByColumn = column.prop;
            this.queryParams.isAsc = column.order;
            this.getList();
        },
    /** 导出按钮操作 */
    downRuleExecl() {
      this.queryParams.ids= this.ids;
      this.queryParams.ruleTypeId=this.queryParamsInit.ruleTypeId;
      this.queryParams.dataBaseType=this.queryParamsInit.dataBaseType;
      this.queryParams.hisVersion=this.queryParamsInit.hisVersion;
        if(this.queryParams.hisVersion){
          this.nodeName=this.nodeName +"_"+ this.queryParams.hisVersion;
        }else{
          this.nodeName= this.nodeName +"_"+ this.dict.type.report_version[0].value;
        }
        this.download('reportworld/rule/downRuleExecl', {
                ...this.queryParams
    }, this.nodeName+`${new Date().getTime()}.xlsx`)
    },
    tableRowStyle({ row, rowIndex}){
        return getTableRowStyle(row,rowIndex,this.ids);
    },
    /** 单击选中行数据 */
    rowClick(row) {
        this.$refs.para.toggleRowSelection(row);
    },
      readExecl(){
        if(this.queryParamsInit.hisVersion){
          this.upload.title = "读取规则文件";
          this.upload.open = true;
          this.$modal.confirm('是否确认读取'+this.queryParamsInit.hisVersion+'版本生成脚本吗？').then(function() {
            return;
          }).then(() => {
          }).catch(() => {this.upload.open = false;});
        }else{
          this.upload.title = "读取规则文件";
          this.upload.open = true;
        }
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(200 != response.code){
          this.$modal.msgError(response.msg);
          return;
        }
        if(this.upload.updateSupport){
          this.download('reportworld/rule/handleDownSql', {}, `RULE_${new Date().getTime()}.sql`)
        }else{
          //打开提交脚本页面
          this.openScript =true;
          this.scriptSqlInfo = response.msg;
          if(this.queryParams.hisVersion){
            this.hisVersion=this.queryParams.hisVersion;
          }else{
            this.hisVersion=this.dict.type.report_version[0].value;
          }
          this.titleScript = "脚本详细信息";
        }
      },
      submitFileFormChild() {
        this.$refs.child.submitForm();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      }
    }
    };
</script>
